import axios from 'axios';
import { CALENDAR } from '../keys';
// 日历
// http://v.juhe.cn/calendar/day?date=2015-1-1&key=您申请的appKey
function formDate(curDate) {
  curDate = curDate ? new Date(curDate) : new Date();
  const date = curDate.getDate();
  const month = curDate.getMonth() + 1;
  const year = curDate.getFullYear();
  return {
    date: `${year}-${month}-${date}`,
    month: `${year}-${month}`,
    year,
    inputDate: `${year}-${String(month).padStart(2, '0')}-${String(
      date
    ).padStart(2, '0')}`
  };
}
let cache = {};
function getCalendar(curDate) {
  const { date, month, year } = formDate(curDate);
  const key = CALENDAR;

  const getDate = () => {
    if (cache[date]) return Promise.resolve(cache[date]);
    return axios
      .get('/calendar/calendar/day', {
        params: { date, key }
      })
      .then(data => {
        return (cache[date] = data);
      });
  };
  const getMonth = () => {
    if (cache[month]) return Promise.resolve(cache[month]);
    return axios
      .get('/calendar/calendar/month', {
        params: { 'year-month': month, key }
      })
      .then(data => {
        return (cache[month] = data);
      });
  };
  const getYear = () => {
    if (cache[year]) return Promise.resolve(cache[year]);
    return axios
      .get('/calendar/calendar/year', { params: { year, key } })
      .then(data => {
        return (cache[year] = data);
      });
  };

  // 这边先把三个请求的响应对象打包导出 ，再在 hooks 中赛选需要的属性
  return Promise.all([getDate(), getMonth()]);
}

export { getCalendar, formDate };

// spread 展开
/*
// 这样得到的 arg 是个数组
return axios.all([getDate(), getMonth(), getYear()])
  .then(arg => {
    console.log(arg);
  });
// 如果我们想展开请求的结果 对应的参数 接收对应的响应结果
*/
